package com.example.archivemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.archivemanagement.common.OperationType;
import com.example.archivemanagement.entity.VisitRecord;
import com.example.archivemanagement.mapper.VisitRecordMapper;
import com.example.archivemanagement.service.StatisticsService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;

@Service
public class StatisticsServiceImpl extends ServiceImpl<VisitRecordMapper, VisitRecord> implements StatisticsService {
    @Override
    public long getTodayVisits() {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(23, 59, 59);

        return baseMapper.selectCount(new QueryWrapper<VisitRecord>()
                .eq("operation_type", OperationType.VISIT.getValue())
                .between("operation_date", startOfDay, endOfDay));
    }

    @Override
    public long getMonthViews() {
        YearMonth currentMonth = YearMonth.now();
        LocalDateTime startOfMonth = currentMonth.atDay(1).atStartOfDay();
        LocalDateTime endOfMonth = currentMonth.atEndOfMonth().atTime(23, 59, 59);

        return baseMapper.selectCount(new QueryWrapper<VisitRecord>()
                .eq("operation_type", OperationType.VIEW.getValue())
                .between("operation_date", startOfMonth, endOfMonth));
    }

    @Override
    public long getDownloadCount() {
        return baseMapper.selectCount(new QueryWrapper<VisitRecord>()
                .eq("operation_type", OperationType.DOWNLOAD.getValue()));
    }

    @Override
    public void addTodayVisits() {
        VisitRecord visitRecord = new VisitRecord();
        visitRecord.setOperationType(OperationType.VISIT);
        visitRecord.setOperationDate(LocalDateTime.now());
        baseMapper.insert(visitRecord);
    }

    @Override
    public void addMonthViews() {
        VisitRecord visitRecord = new VisitRecord();
        visitRecord.setOperationType(OperationType.VIEW);
        visitRecord.setOperationDate(LocalDateTime.now());
        baseMapper.insert(visitRecord);
    }

    @Override
    public void addDownloadCount(String fileName) {
        VisitRecord visitRecord = new VisitRecord();
        visitRecord.setOperationType(OperationType.DOWNLOAD);
        visitRecord.setOperationDate(LocalDateTime.now());
        visitRecord.setFileName(fileName);
        baseMapper.insert(visitRecord);
    }
}
